const Bill = require('../models/Bill');
const db = require('../config/db');

// 定义常量来避免魔法字符串
const BILL_TYPES = {
  INCOME: 'income',
  EXPENSE: 'expense',
  TRANSFER: 'transfer' // 新增转账类型
};

const ERROR_MESSAGES = {
  INVALID_BILL_ID: 'Invalid bill ID',
  BILL_NOT_FOUND: 'Bill not found',
  CATEGORY_REQUIRED: 'Category, amount, type, and date are required',
  INVALID_AMOUNT: 'Amount must be a positive number',
  INVALID_TYPE: 'Type must be either income, expense, or transfer',
  INVALID_DATE_FORMAT: 'Date must be in YYYY-MM-DD format',
  INVALID_CATEGORY_ID: 'Invalid category ID',
  INVALID_ACCOUNT_ID: 'Invalid account ID',
  TRANSFER_ACCOUNTS_REQUIRED: 'Transfer requires both source and target accounts',
  TRANSFER_SAME_ACCOUNT: 'Transfer source and target accounts must be different',
  FAILED_TO_CREATE_BILL: 'Failed to create bill',
  FAILED_TO_UPDATE_BILL: 'Failed to update bill',
  INTERNAL_SERVER_ERROR: 'Internal server error'
};

const HTTP_STATUS = {
  BAD_REQUEST: 400,
  NOT_FOUND: 404,
  INTERNAL_SERVER_ERROR: 500,
  CREATED: 201
};

// 私有方法：构建过滤查询
function buildFilterQuery(baseQuery, filters, params, paramIndex, tableName = 'b') {
  let query = baseQuery;
  let currentIndex = paramIndex;

  // 添加日期过滤器
  if (filters.start_date) {
    query += ` AND ${tableName}.bill_date >= $${currentIndex}`;
    params.push(filters.start_date);
    currentIndex++;
  }

  if (filters.end_date) {
    query += ` AND ${tableName}.bill_date <= $${currentIndex}`;
    params.push(filters.end_date);
    currentIndex++;
  }

  // 添加类型过滤器
  if (filters.type) {
    query += ` AND ${tableName}.type = $${currentIndex}`;
    params.push(filters.type);
    currentIndex++;
  }

  // 添加分类过滤器
  if (filters.category_id) {
    query += ` AND ${tableName}.category_id = $${currentIndex}`;
    params.push(filters.category_id);
    currentIndex++;
  }

  // 添加账户过滤器
  if (filters.account_id) {
    query += ` AND ${tableName}.account_id = $${currentIndex}`;
    params.push(filters.account_id);
    currentIndex++;
  }

  // 添加搜索过滤器
  if (filters.search) {
    query += ` AND (${tableName}.title ILIKE $${currentIndex} OR ${tableName}.description ILIKE $${currentIndex})`;
    params.push(`%${filters.search}%`);
    currentIndex++;
  }

  return { query, params, currentIndex };
}

// 验证用户对账单的访问权限
async function validateUserBillAccess(user_id, bill_id) {
  try {
    const result = await db.query(
      'SELECT * FROM bills WHERE id = $1 AND user_id = $2',
      [bill_id, user_id]
    );
    
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Validate user bill access error:', error);
    return null;
  }
}

// 验证分类是否存在且属于用户（或为默认分类）
async function validateCategoryAccess(user_id, category_id) {
  try {
    const result = await db.query(
      'SELECT id FROM categories WHERE id = $1 AND (user_id = $2 OR user_id = 0)',
      [category_id, user_id]
    );
    
    return result.rows.length > 0;
  } catch (error) {
    console.error('Validate category access error:', error);
    return false;
  }
}

// 验证账户是否存在且属于用户
async function validateAccountAccess(user_id, account_id) {
  try {
    const result = await db.query(
      'SELECT id FROM accounts WHERE id = $1 AND user_id = $2',
      [account_id, user_id]
    );
    
    return result.rows.length > 0;
  } catch (error) {
    console.error('Validate account access error:', error);
    return false;
  }
}

// Create a new bill
async function createBill(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const billData = req.body;
    
    // 验证必填字段
    if (!billData.amount || !billData.type || !billData.bill_date) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.CATEGORY_REQUIRED });
    }
    
    // 对于非转账类型，还需要验证分类ID
    if (billData.type !== BILL_TYPES.TRANSFER && !billData.category_id) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.CATEGORY_REQUIRED });
    }
    
    // 验证金额
    const amount = parseFloat(billData.amount);
    if (isNaN(amount) || amount <= 0) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_AMOUNT });
    }
    
    // 验证类型
    if (![BILL_TYPES.INCOME, BILL_TYPES.EXPENSE, BILL_TYPES.TRANSFER].includes(billData.type)) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_TYPE });
    }
    
    // 验证转账类型特殊要求
    if (billData.type === BILL_TYPES.TRANSFER) {
      // 验证源账户和目标账户
      if (!billData.account_id || !billData.transfer_to_account_id) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.TRANSFER_ACCOUNTS_REQUIRED });
      }
      
      // 验证源账户和目标账户不能相同
      if (billData.account_id === billData.transfer_to_account_id) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.TRANSFER_SAME_ACCOUNT });
      }
      
      // 验证账户是否存在且属于用户
      const isSourceAccountValid = await validateAccountAccess(user_id, billData.account_id);
      if (!isSourceAccountValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
      
      const isTargetAccountValid = await validateAccountAccess(user_id, billData.transfer_to_account_id);
      if (!isTargetAccountValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
    } else {
      // 非转账类型需要验证分类
      const isCategoryValid = await validateCategoryAccess(user_id, billData.category_id);
      if (!isCategoryValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_CATEGORY_ID });
      }
    }
    
    // 验证日期格式
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateRegex.test(billData.bill_date)) {
      console.log('日期格式验证失败:', billData.bill_date);
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_DATE_FORMAT });
    }
    
    // 验证账户是否存在且属于用户（如果提供了账户ID）
    if (billData.account_id && billData.type !== BILL_TYPES.TRANSFER) {
      const isAccountValid = await validateAccountAccess(user_id, billData.account_id);
      if (!isAccountValid) {
        console.log('账户验证失败:', billData.account_id);
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
    }
    
    // 创建账单
    const result = await db.query(
      `INSERT INTO bills (user_id, category_id, title, amount, type, bill_date, description, payment_method, account_id, transfer_to_account_id) 
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *`,
      [user_id, billData.category_id, billData.title, billData.amount, billData.type, billData.bill_date, billData.description, billData.payment_method, billData.account_id, billData.transfer_to_account_id]
    );
    
    if (!result || !result.rows || result.rows.length === 0) {
      return res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.FAILED_TO_CREATE_BILL });
    }
    
    // 获取创建的账单详情，包括分类和账户名称
    const createdResult = await db.query(
      `SELECT b.*, c.name as category_name, a.name as account_name, ta.name as transfer_to_account_name FROM bills b
       LEFT JOIN categories c ON b.category_id = c.id
       LEFT JOIN accounts a ON b.account_id = a.id
       LEFT JOIN accounts ta ON b.transfer_to_account_id = ta.id
       WHERE b.id = $1 AND b.user_id = $2`,
      [result.rows[0].id, user_id]
    );
    
    const bill = Bill.fromRow(createdResult.rows[0]);
    
    res.status(HTTP_STATUS.CREATED).json({
      message: 'Bill created successfully',
      bill: {
        ...bill.toJSON(),
        category_name: createdResult.rows[0].category_name,
        account_name: createdResult.rows[0].account_name,
        transfer_to_account_name: createdResult.rows[0].transfer_to_account_name
      }
    });
  } catch (error) {
    console.error('Create bill error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

// Get bills with pagination and filtering
async function getBills(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    // 构建过滤器
    const filters = {
      start_date: req.query.start_date,
      end_date: req.query.end_date,
      category_id: req.query.category_id,
      account_id: req.query.account_id,
      type: req.query.type,
      search: req.query.search
    };
    
    // 构建查询
    let query = `SELECT b.*, c.name as category_name, a.name as account_name, ta.name as transfer_to_account_name FROM bills b 
                 LEFT JOIN categories c ON b.category_id = c.id 
                 LEFT JOIN accounts a ON b.account_id = a.id
                 LEFT JOIN accounts ta ON b.transfer_to_account_id = ta.id
                 WHERE b.user_id = $1`;
    let params = [user_id];
    let paramIndex = 2;
    
    // 使用公共方法构建过滤查询
    const filterResult = buildFilterQuery(query, filters, params, paramIndex);
    query = filterResult.query;
    paramIndex = filterResult.currentIndex;
    params = filterResult.params;
    
    // 添加排序和分页
    query += ` ORDER BY b.bill_date DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
    params.push(limit, offset);
    
    // 获取账单
    const result = await db.query(query, params);
    
    const bills = result.rows.map(row => {
      const bill = Bill.fromRow(row);
      return {
        ...bill.toJSON(),
        category_name: row.category_name,
        account_name: row.account_name,
        transfer_to_account_name: row.transfer_to_account_name
      };
    });
    
    // 构建计数查询
    let countQuery = `SELECT COUNT(*) FROM bills b 
                      LEFT JOIN categories c ON b.category_id = c.id 
                      LEFT JOIN accounts a ON b.account_id = a.id
                      LEFT JOIN accounts ta ON b.transfer_to_account_id = ta.id
                      WHERE b.user_id = $1`;
    let countParams = [user_id];
    let countParamIndex = 2;
    
    // 为计数查询使用相同的过滤器
    const countFilterResult = buildFilterQuery(countQuery, filters, countParams, countParamIndex, 'b');
    countQuery = countFilterResult.query;
    countParams = countFilterResult.params;
    
    // 获取总数
    const countResult = await db.query(countQuery, countParams);
    const total = parseInt(countResult.rows[0].count);
    
    res.json({
      bills,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('Get bills error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

// Get a specific bill by ID
async function getBillById(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const bill_id = parseInt(req.params.id);
    
    // 验证账单ID
    if (isNaN(bill_id)) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_BILL_ID });
    }
    
    // 验证用户对账单的访问权限
    const billRecord = await validateUserBillAccess(user_id, bill_id);
    if (!billRecord) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.BILL_NOT_FOUND });
    }
    
    // 获取账单详情，包括分类和账户名称
    const result = await db.query(
      `SELECT b.*, c.name as category_name, a.name as account_name, ta.name as transfer_to_account_name FROM bills b
       LEFT JOIN categories c ON b.category_id = c.id
       LEFT JOIN accounts a ON b.account_id = a.id
       LEFT JOIN accounts ta ON b.transfer_to_account_id = ta.id
       WHERE b.id = $1 AND b.user_id = $2`,
      [bill_id, user_id]
    );
    
    if (!result || !result.rows || result.rows.length === 0) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.BILL_NOT_FOUND });
    }
    
    const bill = Bill.fromRow(result.rows[0]);
    
    res.json({
      bill: {
        ...bill.toJSON(),
        category_name: result.rows[0].category_name,
        account_name: result.rows[0].account_name,
        transfer_to_account_name: result.rows[0].transfer_to_account_name
      }
    });
  } catch (error) {
    console.error('Get bill error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

// Update a bill
async function updateBill(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const bill_id = parseInt(req.params.id);
    const { category_id, title, amount, type, bill_date, description, payment_method, account_id, transfer_to_account_id } = req.body;
    
    // 验证用户对账单的访问权限
    const existingBill = await validateUserBillAccess(user_id, bill_id);
    if (!existingBill) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.BILL_NOT_FOUND });
    }
    
    // 验证转账类型特殊要求
    if (type === BILL_TYPES.TRANSFER) {
      // 验证源账户和目标账户
      if (!account_id || !transfer_to_account_id) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.TRANSFER_ACCOUNTS_REQUIRED });
      }
      
      // 验证源账户和目标账户不能相同
      if (account_id === transfer_to_account_id) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.TRANSFER_SAME_ACCOUNT });
      }
      
      // 验证账户是否存在且属于用户
      const isSourceAccountValid = await validateAccountAccess(user_id, account_id);
      if (!isSourceAccountValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
      
      const isTargetAccountValid = await validateAccountAccess(user_id, transfer_to_account_id);
      if (!isTargetAccountValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
    } else if (category_id) {
      // 非转账类型需要验证分类（如果提供了分类ID）
      const isCategoryValid = await validateCategoryAccess(user_id, category_id);
      if (!isCategoryValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_CATEGORY_ID });
      }
    }
    
    // 验证账户是否存在且属于用户（如果提供了账户ID）
    if (account_id && type !== BILL_TYPES.TRANSFER) {
      const isAccountValid = await validateAccountAccess(user_id, account_id);
      if (!isAccountValid) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_ACCOUNT_ID });
      }
    }
    
    // 处理金额（如果提供了）
    let amountValue = existingBill.amount;
    if (amount !== undefined) {
      const amountNum = parseFloat(amount);
      if (isNaN(amountNum) || amountNum <= 0) {
        return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: ERROR_MESSAGES.INVALID_AMOUNT });
      }
      amountValue = amountNum;
    }
    
    // 使用COALESCE更新账单，提供字段或保留现有值
    const result = await db.query(
      `UPDATE bills SET 
       category_id = COALESCE($1, category_id), 
       title = COALESCE($2, title), 
       amount = $3, 
       type = COALESCE($4, type), 
       bill_date = COALESCE($5, bill_date), 
       description = COALESCE($6, description), 
       payment_method = COALESCE($7, payment_method),
       account_id = COALESCE($8, account_id),
       transfer_to_account_id = COALESCE($9, transfer_to_account_id),
       updated_at = CURRENT_TIMESTAMP 
       WHERE id = $10 AND user_id = $11 RETURNING *`,
      [
        category_id, 
        title, 
        amountValue, 
        type, 
        bill_date, 
        description, 
        payment_method, 
        account_id,
        transfer_to_account_id,
        bill_id, 
        user_id
      ]
    );
    
    if (!result || !result.rows || result.rows.length === 0) {
      return res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.FAILED_TO_UPDATE_BILL });
    }
    
    // 获取更新后的账单详情，包括分类和账户名称
    const updatedResult = await db.query(
      `SELECT b.*, c.name as category_name, a.name as account_name, ta.name as transfer_to_account_name FROM bills b
       LEFT JOIN categories c ON b.category_id = c.id
       LEFT JOIN accounts a ON b.account_id = a.id
       LEFT JOIN accounts ta ON b.transfer_to_account_id = ta.id
       WHERE b.id = $1 AND b.user_id = $2`,
      [bill_id, user_id]
    );
    
    const bill = Bill.fromRow(updatedResult.rows[0]);
    
    res.json({
      message: 'Bill updated successfully',
      bill: {
        ...bill.toJSON(),
        category_name: updatedResult.rows[0].category_name,
        account_name: updatedResult.rows[0].account_name,
        transfer_to_account_name: updatedResult.rows[0].transfer_to_account_name
      }
    });
  } catch (error) {
    console.error('Update bill error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

// Delete a bill
async function deleteBill(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const bill_id = parseInt(req.params.id);
    
    // 验证用户对账单的访问权限
    const existingBill = await validateUserBillAccess(user_id, bill_id);
    if (!existingBill) {
      return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.BILL_NOT_FOUND });
    }
    
    // 删除账单
    await db.query(
      `DELETE FROM bills WHERE id = $1 AND user_id = $2`,
      [bill_id, user_id]
    );
    
    res.json({
      message: 'Bill deleted successfully'
    });
  } catch (error) {
    console.error('Delete bill error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

// Get bill statistics
async function getBillStats(req, res) {
  try {
    const user_id = req.userId; // Set by auth middleware
    const { start_date, end_date, account_id } = req.query;
    
    // 验证日期格式（如果提供了）
    if (start_date && !/^\d{4}-\d{2}-\d{2}$/.test(start_date)) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: 'Invalid start_date format. Must be YYYY-MM-DD' });
    }
    
    if (end_date && !/^\d{4}-\d{2}-\d{2}$/.test(end_date)) {
      return res.status(HTTP_STATUS.BAD_REQUEST).json({ error: 'Invalid end_date format. Must be YYYY-MM-DD' });
    }
    
    // 构建日期过滤器
    let dateFilter = '';
    let params = [user_id];
    let paramIndex = 2;
    
    if (start_date) {
      dateFilter += ` AND bill_date >= $${paramIndex}`;
      params.push(start_date);
      paramIndex++;
    }
    
    if (end_date) {
      dateFilter += ` AND bill_date <= $${paramIndex}`;
      params.push(end_date);
      paramIndex++;
    }
    
    // 添加账户过滤器
    if (account_id) {
      dateFilter += ` AND account_id = $${paramIndex}`;
      params.push(account_id);
      paramIndex++;
    }
    
    // 获取总收入、支出和转账
    const summaryResult = await db.query(
      `SELECT 
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.INCOME}' THEN amount ELSE 0 END), 0) as total_income,
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.EXPENSE}' THEN amount ELSE 0 END), 0) as total_expense,
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.TRANSFER}' THEN amount ELSE 0 END), 0) as total_transfer,
        COUNT(CASE WHEN type = '${BILL_TYPES.INCOME}' THEN 1 END) as income_count,
        COUNT(CASE WHEN type = '${BILL_TYPES.EXPENSE}' THEN 1 END) as expense_count,
        COUNT(CASE WHEN type = '${BILL_TYPES.TRANSFER}' THEN 1 END) as transfer_count
       FROM bills WHERE user_id = $1${dateFilter}`,
      params
    );
    
    const summaryRow = summaryResult.rows[0] || {};
    const summary = {
      total_income: parseFloat(summaryRow.total_income || 0),
      total_expense: parseFloat(summaryRow.total_expense || 0),
      total_transfer: parseFloat(summaryRow.total_transfer || 0),
      net_income: parseFloat(summaryRow.total_income || 0) - parseFloat(summaryRow.total_expense || 0),
      income_count: parseInt(summaryRow.income_count || 0),
      expense_count: parseInt(summaryRow.expense_count || 0),
      transfer_count: parseInt(summaryRow.transfer_count || 0)
    };
    
    // 获取支出最多的分类
    const topCategoriesResult = await db.query(
      `SELECT 
        c.name as category_name,
        COALESCE(SUM(b.amount), 0) as total_amount,
        COUNT(b.id) as bill_count
       FROM bills b
       LEFT JOIN categories c ON b.category_id = c.id
       WHERE b.user_id = $1 AND b.type = '${BILL_TYPES.EXPENSE}'${dateFilter}
       GROUP BY c.name
       ORDER BY total_amount DESC
       LIMIT 5`,
      params
    );
    
    const topCategories = topCategoriesResult.rows ? topCategoriesResult.rows.map(cat => ({
      category_name: cat.category_name,
      total_amount: parseFloat(cat.total_amount),
      bill_count: parseInt(cat.bill_count)
    })) : [];
    
    // 获取每日支出趋势
    const trendResult = await db.query(
      `SELECT 
        DATE(bill_date) as date,
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.INCOME}' THEN amount ELSE 0 END), 0) as income,
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.EXPENSE}' THEN amount ELSE 0 END), 0) as expense,
        COALESCE(SUM(CASE WHEN type = '${BILL_TYPES.TRANSFER}' THEN amount ELSE 0 END), 0) as transfer
       FROM bills
       WHERE user_id = $1${dateFilter}
       GROUP BY DATE(bill_date)
       ORDER BY date DESC
       LIMIT 30`,
      params
    );
    
    const trend = trendResult.rows ? trendResult.rows.map(t => ({
      date: t.date,
      income: parseFloat(t.income),
      expense: parseFloat(t.expense),
      transfer: parseFloat(t.transfer)
    })) : [];
    
    res.json({
      summary: summary,
      top_categories: topCategories,
      trend: trend
    });
  } catch (error) {
    console.error('Get bill stats error:', error.stack);
    res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR });
  }
}

module.exports = {
  createBill,
  getBills,
  getBillById,
  updateBill,
  deleteBill,
  getBillStats
};